package com.rency.ues.webapp.interceptors;

import com.rency.ues.webapp.common.Constants;
import org.rency.common.utils.domain.SYSDICT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class DefaultInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(DefaultInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI().toString();
        String referer = request.getHeader("Referer");
        String path = request.getServletPath();
        logger.debug("goto page [{}] from [{}].",uri,referer);
        if(uri.endsWith(".json")){
            return true;
        }
        if(Constants.INTERCEPTOR_EXCLUDE_URLS.contains(path)){
            return true;
        }
        HttpSession session = request.getSession();
        if(session.getAttribute(SYSDICT.SESSION_USER_KEY) != null){
            return true;
        }
        response.sendRedirect(request.getContextPath().concat(Constants.URL_LOGIN_INPUT));
        return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	}
	
}
